<template>
	<!-- 上传文件 -->
	<!-- padding: 24rpx; -->
	<view class=" " :class="['upload',!notCard?'card':'']"
		:style="{padding: padding,width:'calc(100% - '+padding+' - '+padding+')'}">
		<view class="box">
			<view class="lable" v-if="lable">
				{{ lable }}
			</view>
			<view class="upload-btn" v-if="!notUpload">
				<wd-upload custom-class="wd-upload-custom-class-custom-btn not-show-list" image-mode="aspectFill"
					:multiple="true" @change="wdUploadChange" :before-upload="wdBeforeUpload">
					<view class="upload-btn-content">
						上传文件
					</view>
				</wd-upload>
			</view>
			<view class="file-list">
				<view class="file-list-item" v-for="(item,index) in fileList">
					<view class="file-list-item-icon" v-if="!notUpload">
						<text class="iconfont icon-shangchuan"></text>
					</view>
					<view class="file-list-item-icon" v-else>
						<text class="iconfont icon-file"></text>
					</view>
					<view class="file-list-item-info">
						<view class="file-list-item-info-name text-ellipsis">
							{{ item.name || item.path|| item.url}}
						</view>
					</view>
					<view class="file-list-item-delete" v-if="!notUpload" @click="deleteFile(item,index)">
						<text class="iconfont icon-guanbi"></text>
					</view>
					<view class="file-list-item-delete" v-else @click="getFile(item,index)">
						<text class="iconfont icon-xiazai"></text>
					</view>
				</view>
			</view>
		</view>
		<!-- 	<view class="tips">
			支持扩展名：.rar .zip .doc .docx .pdf .jpg...
		</view> -->
	</view>
	<view class="upload__error-message">
		{{ errorMessage }}
	</view>
</template>

<script lang="ts">
	import { defineComponent, ref, computed, onMounted, watch } from 'vue';
	import { FORM_KEY } from '@/uni_modules/wot-design-uni/components/wd-form/types'
	import { useParent } from '@/uni_modules/wot-design-uni/components/composables/useParent'
	import { uploadImgFile } from "@/api/index"
	export default defineComponent({
		emits: [
			'update:modelValue'
		],
		props: {
			modelValue: {
				type: String,
				default: ""
			},
			prop: {
				type: String,
				default: ""
			},
			notUpload: {
				type: Boolean,
				default: false
			},
			notCard: {
				type: Boolean,
				default: false
			},
			padding: {
				type: String,
				default: "24rpx"
			},
			lable: {
				type: String,
			}
		},
		setup(props, ctx) {
			const { parent: form } = useParent(FORM_KEY)
			// 文件列表
			const fileList : any = ref([]);
			// 上传文件
			const wdBeforeUpload = (event : any) => {
				const uploadList = [];
				for (let i = 0; i < event.files.length; i++) {
					uploadList[i] = uploadImgFile(event.files[i].path);
				}
				Promise.all(uploadList).then(res => {
					let list = res.map(item => ({ ...item.data, url: item.data.src }))
					fileList.value.push(...list);
					// 触发事件，通知父组件更新值。
					ctx.emit('update:modelValue', fileList.value.map((item : { url : any; }) => item.url).join(','));
					// 或者使用vue3的语法糖，直接使用emit触发事件。
					// this.emit('update:modelValue', fileList.value.map(item => item.url).join(','));
					// 或者使用vue3的语法糖，直接使用emit触发事件。
				}).catch(err => {
					console.log(err, '上传失败');
				});
				// uploadFile
				// uploadFile
				// fileList.value.push(...event.files);
				event.resolve(false);
			}
			// 删除文件
			const deleteFile = (file : any, fileIndex : number) => {
				fileList.value = fileList.value.filter((i : any, index : number) => {
					return fileIndex != index
				})
			}
			const getFile = (file : any, fileIndex : number) => {
				// #ifndef H5
				uni.$wdToast.loading("下载中...")
				uni.downloadFile({
					url: file.url, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('下载成功',);
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: (image) => {
									console.log(image)
									uni.$wdToast.close();
									uni.$wdToast.show("下载成功-已保存到相册")
								}
							});
						}
					}
				});
				// #endif
			}
			// 表单校验错误信息
			const errorMessage = computed(() => {
				if (form && props.prop && form.errorMessages && form.errorMessages[props.prop]) {
					return form.errorMessages[props.prop]
				} else {
					return ''
				}
			})
			watch(() => props.modelValue, () => {
				if (props.modelValue.length > 0) {
					let arr = props.modelValue.split(",");
					let list = Array.from(new Set(arr)).map(item => ({ url: item }))
					fileList.value = list;
				}
			}, {
				deep: true,
				immediate: true
			})
			onMounted(() => {
				// if (props.modelValue) {
				// 	let list = props.modelValue.split(",").map(item => ({ url: item }))
				// 	fileList.value.push(...list);
				// 	console.log(props.modelValue);
				// }
			})
			return {
				errorMessage,
				fileList,
				wdBeforeUpload,
				deleteFile,
				getFile,
			}
		},
	});
</script>
<style lang="scss" scoped>
	@import "@/uni_modules/wot-design-uni/components/common/abstracts/_mixin.scss";
	@import "@/uni_modules/wot-design-uni/components/common/abstracts/variable.scss";

	.upload__error-message {
		color: $-form-item-error-message-color;
		font-size: $-form-item-error-message-font-size;
		line-height: $-form-item-error-message-line-height;
		text-align: left;
		vertical-align: middle;
	}
</style>
<style lang="less" scoped>
	.upload {

		// width: calc(100% - 24rpx - 24rpx);

		>.box {
			display: flex;
			align-items: flex-start;
			flex-direction: column;

			.lable {
				font-size: 32rpx;
				margin-bottom: 24rpx;
			}

			.upload-btn {
				background: #C91C1F;
				border-radius: 17rpx;

				font-family: PingFang;
				font-weight: bold;
				font-size: 22rpx;
				color: #FFFFFF;

				padding: 4rpx 10rpx;
				margin-top: 12rpx;
				text-align: center;
				margin-bottom: 8rpx;
			}


			.file-list {
				width: 100%;
				padding: 0;
			}
		}

		>.tips {
			font-family: PingFang;
			font-weight: 400;
			font-size: 22rpx;
			color: #999999;
			margin-top: 12rpx;
		}


	}

	.file-list {
		padding: 0 18rpx;

		&-item {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			padding: 12rpx 0;

			&-icon {
				width: 40rpx;
				color: #4A54FF;
			}

			&-info {
				display: flex;
				width: calc(100% - 80rpx);
				color: #4A54FF;
			}

			&-delete {
				width: 40rpx;
				font-size: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>